/**
 * @Author: jipeng.Li
 * @Date: 2021-03-03 16:45:21
 * @LastEditors: jipeng.Li
 * @LastEditTime: 2021-03-12 09:53:21
 * @Description: 申请拨油
 */
import React, { Component } from 'react';
import { Modal, NativeModules, SafeAreaView, StyleSheet, Text, TouchableOpacity, View } from 'react-native';
import { fontColorCoffee, mainBgColorLightGray, mainBgColorWhite, px2dp } from '@/styles';
import oil from '@/api/oil';
import { msg, Button } from '@/common';
import api from '@/api';
import * as goods from '@/api/goods';
import FictitiousOilCard from './components/fictitious-oil-card';
import EntityOilCard from './components/entity-oil-card';
import RechargePriceChoice from './components/recharge-price-choice';
import RechargeResultModal from './components/reacharge-result-modal';
import ConfirmPumpOilModal from './components/confirm-pump-oil-modal';

const { Submit } = Button;

export default class PumpOil extends Component {
  constructor(props) {
    super(props);
    this.state = {
      currentPosition: {},
      systemInfo: {},
      cardData: {},
      price: '500',
      modalIsShow: false,
      modalType: 'result',
      cardType: 0, // 油卡类型 0 虚拟 1 实体
      orderNo: '', // 生成的订单id 用来跳转查询订单详情
      disabled: true,
    };
  }

  priceList = ['500', '1000', '1500', '2000', '3000', '5000']

  componentDidMount() {
    const { navigation } = this.props;
    const state = navigation.state || {};
    const params = state.params || {};
    const { cardType, cardData } = params;
    this.setState({ cardData, cardType }, () => {
      if (!cardType) {
        this.getFictitiousCardById();
      }
    });
    this.getCurrentPosition();
    this.getSystemInfo();
  }

  componentWillUnmount() {
    msg.emit('setUpQrCodeInterval');
  }

  render() {
    const { price, cardType, cardData, modalIsShow, modalType, disabled } = this.state;

    const tipsCell = [
      {
        tip: cardType ? '卡号：' : '拨油法人',
        text: cardType ? this.convertCardData().cardNumber : this.convertCardData().companyName
      },
      { tip: cardType ? '油卡类型：' : '拨油商户', text: this.convertCardData().companyType },
    ];
    return (
      <SafeAreaView style={styles.container}>
        <View style={styles.cardView}>
          <View style={styles.oilCard}>
            {
              cardType ? (
                <EntityOilCard
                  {...this.convertCardData()}
                />
              ) : (
                <FictitiousOilCard
                  {...this.convertCardData()}
                />
              )
            }
            <RechargePriceChoice
              price={price}
              priceList={this.priceList}
              priceItemClick={item => this.setState({ price: item })}
              onChangePriceText={price => this.setState({ price: price })}
            />

            <Submit
              text='申请拨油'
              boxStyle={{
                width: px2dp(654),
                height: px2dp(96),
                borderRadius: px2dp(12),
                overflow: 'hidden',

              }}
              btnStyle={{
                width: px2dp(654),
                height: px2dp(96),
              }}
              btnTextStyle={{
                fontSize: px2dp(36),
              }}
              onClick={() => {
                if (parseFloat(price) > 0) {
                  this.setState({ modalIsShow: true, modalType: 'confirm' });
                } else {
                  msg.emit('app:tip', { text: '请输入大于0的金额' });
                }
              }}
            />
          </View>
        </View>
        <Modal
          animationType='slide'
          transparent={false}
          visible={modalIsShow}
        >
          {
            modalType === 'result' ? ( // 成功结果模态框
              <RechargeResultModal
                price={`¥ ${this.formatAmount(price)}`}
                completeClick={this.resultCompleteClick}
                gotoOrderDetails={this.gotoOrderDetails}
              />
            ) : ( // 确定拨油模态框
              <ConfirmPumpOilModal
                price={`¥ ${this.formatAmount(price)}`}
                tipsCell={tipsCell}
                disabled={disabled}
                confirmClick={this.allotApply}
                clearClick={() => this.setState({ modalIsShow: false })}
              />
            )
          }
        </Modal>
      </SafeAreaView>
    );
  }

  // 根据油卡类型取不同字段展示
  convertCardData = () => {
    const { cardData, cardType } = this.state;
    if (cardType) {
      return {
        owner: cardData.name || '',
        companyType: cardData.supplierName || '',
        cardNumber: cardData.oilcardNo || ''
      };
    }
    return {
      balance: cardData.total || '', // 余额
      companyType: cardData.allianceName || '', // 商户类型
      companyName: cardData.leaglName || '', // 法人名称
      owner: cardData.caronwerCustName || '', // 所有人
      driverName: cardData.driverName || '', // 司机名字
      driverMobile: cardData.driverMobile || '', // 司机电话
    };
  }

  formatAmount = (data, num) => {
    let n = num || 2;
    if (data) {
      return Number(data).toFixed(n).replace(/(\d)(?=(\d{3})+\.)/g, '$1,');
    }
    if (Number(data) === 0) {
      return Number(data).toFixed(2);
      if (data === 0) {
        return Number(data).toFixed(n);
      }
    }
  }

  // 获取当前定位
  getCurrentPosition = () => {
    // 当前定位
    NativeModules.MapModule.getCurrentPosition().then((resPosition) => {
      if (resPosition.city !== null && resPosition.city !== undefined) {
        this.setState({ currentPosition: resPosition });
      } else {
        msg.emit('app:tip', { text: '获取地理位置信息失败' });
      }
    });
  };

  // 获取设备信息
  getSystemInfo = () => {
    NativeModules.BridgeManager.getSystemInfo(systemInfo => {
      this.setState({ systemInfo });
    });
  }

  // 结果完成按钮
  resultCompleteClick = () => {
    const { cardType } = this.state;
    this.setState({ modalIsShow: false }, () => {
      msg.emit('router: goToNext', {
        routeName: 'Order',
        cardType
      });
    });
  }

  // 结果交易记录
  gotoOrderDetails = () => {
    const { cardType, orderNo } = this.state;
    this.setState({ modalIsShow: false }, () => {
      if (cardType) {
        msg.emit('router: goToNext', {
          orderNo: orderNo,
          routeName: 'OilOrderDetail',
          toDetail: 0
        });
      } else {
        msg.emit('router: goToNext', {
          cardData: { id: orderNo },
          routeName: 'FictitiousOilCardOrderDetail',
        });
      }
    });
  }

  /**
   * 接口
   */
  allotApply = () => {
    const { cardType } = this.state;
    if (cardType) { // 实体拨油
      this.entityCardPumpOil();
    } else { // 虚拟拨油
      this.fictitiousCardPumpOil();
    }
  }

  // 请求虚拟油卡数据
  getFictitiousCardById = () => {
    const { cardData } = this.state;
    oil.getAuthById({ id: cardData.id }).then(res => {
      if (res.success) {
        this.setState({ cardData: res.data });
      } else {
        msg.emit('app:tip', { text: res.msg || '连接错误' });
        msg.emit('router: back');
      }
    });
  }

  // 虚拟油卡确认拨油
  fictitiousCardPumpOil = () => {
    const { price, cardData, disabled } = this.state;
    if (!disabled) return;
    this.setState({ disabled: false });
    // setTimeout(() => {
    //   this.setState({ disabled: true });
    // }, 1000);
    oil.allotApply({
      amount: price,
      carownerAccountId: cardData.accountCarownerId,
    }).then(res => {
      if (res.success) {
        this.setState({ orderNo: res.data.id, modalType: 'result', disabled: true }); // 获取订单号 用于跳转订单详情
      } else {
        this.setState({ disabled: true });
        msg.emit('app:tip', { text: res.msg || '申请失败' });
      }
    }).catch(err => {
      this.setState({ disabled: true });
    });
  }

  // 实体油卡拨油 获取商品数据 -> 确认订单 -> 提交订单 -> 订单支付
  entityCardPumpOil = () => {
    const { price, currentPosition, systemInfo, disabled } = this.state;
    if (!disabled) return;
    this.setState({ disabled: false });
    // setTimeout(() => {
    //   this.setState({ disabled: true });
    // }, 1000);
    api.shop.shopOilList({ gcCode: 'ykcz' })
      .then(res => { // 油品商品数据接口回调
        this.isSuccess(res);
        return api.order.confirmOrder({
          oilCardData: {
            goodsId: res.data.id,
            goodsNum: 1,
            money: price,
            oilcardNo: this.convertCardData().cardNumber,
          },
          orderType: 1,
        });
      })
      .then(res => { // 确认订单回调
        this.isSuccess(res);
        return api.order.submitOrder({
          integral: 0,
          orderType: 1,
          identity: 1,
          oilcardData: {
            goodsId: res.data.oilCardData.goodsId,
            goodsNum: 1,
            money: price,
            oilcardNo: this.convertCardData().cardNumber,
          },
        });
      })
      .then(res => { // 提交订单回调
        this.isSuccess(res);
        this.setState({ orderNo: res.data.orderNo }); // 获取订单号 用于跳转订单详情
        const { longitude, latitude } = currentPosition;
        const { appVersion, appType, deviceId, deviceBankId, ipVersion, ipAddress, Mac, simCardNumber, simCardNum, deviceType, deviceName, interIpAddress } = systemInfo;
        const params = {
          orderNo: res.data.orderNo,
          paychannel: 11,
          source: 'XMGJ',
          appType,
          appVersion,
          lbsInfo: `${latitude}/${longitude}`,
          router: 'Order',
          // 风控参数非必传传
          deviceId,
          deviceBankId,
          ipVersion,
          ipAddress,
          mac: Mac,
          simCardNumber,
          simCardNum,
          deviceType,
          deviceName,
          interIpAddress
        };
        return goods.featchOrderConfirmPay(params);
      })
      .then(res => { // 订单支付回调
        this.isSuccess(res);
        this.setState({ modalType: 'result', disabled: true });
      })
      .catch(err => { // 任意一个接口异常提示
        this.setState({ modalIsShow: false, disabled: true }, () => {
          msg.emit('app:messageBox', {
            isVisible: true,
            title: '提示',
            text: err || '请求错误',
            okText: '确定',
            isClickBg: false,
          });
        });
      });
  }

  isSuccess = (res) => {
    if (!res.success) {
      throw res.msg;
    }
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: mainBgColorLightGray,
  },
  cardView: {
    flex: 1,
    backgroundColor: mainBgColorWhite,
    borderRadius: px2dp(24),
    marginTop: px2dp(180),
    marginBottom: px2dp(260),
    marginHorizontal: px2dp(20)
  },
  oilCard: {
    position: 'absolute',
    top: px2dp(-155),
    width: '100%',
    alignItems: 'center',
  },
  btn: {
    width: '100%',
    height: px2dp(96),
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: fontColorCoffee,
    borderRadius: px2dp(12)
  },
});
